<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="专业" prop="major">
        <el-select v-model="formData.major" placeholder="请选择专业" disabled>
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MAJOR)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="studentNumber">
        <el-input v-model="formData.studentNumber" placeholder="请输入学号" disabled />
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <el-input v-model="formData.studentName" placeholder="请输入姓名" disabled />
      </el-form-item>
      <el-form-item label="类别" prop="scholarshipCategory">
        <el-select v-model="formData.scholarshipCategory" placeholder="请选择奖学金类别">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SCHOLARSHIP_CATEGORY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="scholarshipName">
        <el-input v-model="formData.scholarshipName" placeholder="请输入奖学金名称" />
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-select v-model="formData.level" placeholder="请选择级别">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="授予单位" prop="awardingAuthority">
        <el-input v-model="formData.awardingAuthority" placeholder="请输入授予单位" />
      </el-form-item>
      <el-form-item label="获得时间" prop="awardDate">
        <el-date-picker
          v-model="formData.awardDate"
          type="date"
          value-format="x"
          placeholder="选择获得时间"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <p style="font-size: 14px; line-height: 1.6; color: #333">
            注:
            <br />
            1. 本表统计2020年9月1日-2021年8月31日这学年在校本科生所获得的各类奖学金。
            <br />
            2. “奖学金类别”填以下类型：
            <br />
            &nbsp;&nbsp;&nbsp;&nbsp;（1）政府奖学金：指学生获得的由各级政府出资设立的奖学金；
            <br />
            &nbsp;&nbsp;&nbsp;&nbsp;（2）社会奖学金：指学生获得的由政府之外的其他社会机构或个人出资设立的奖学金；
            <br />
            &nbsp;&nbsp;&nbsp;&nbsp;（3）学校奖学金：指学生获得的由学校出资设立的奖学金；
            <br />
            3. “级别”填国家级、省部级、市级、校级等。
          </p>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as ScholarshipApi from '@/api/data/scholarship'
import { getUserProfile } from '@/api/system/user/profile'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  major: undefined,
  studentNumber: undefined,
  studentName: undefined,
  scholarshipCategory: undefined,
  scholarshipName: undefined,
  level: undefined,
  awardingAuthority: undefined,
  awardDate: undefined,
  remark: undefined,
  status: undefined,
  reason: undefined
})
const formRules = reactive({
  major: [{ required: true, message: '专业不能为空', trigger: 'change' }],
  studentNumber: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
  studentName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  scholarshipCategory: [{ required: true, message: '奖学金类别不能为空', trigger: 'change' }],
  scholarshipName: [{ required: true, message: '奖学金名称不能为空', trigger: 'blur' }],
  level: [{ required: true, message: '级别不能为空', trigger: 'change' }],
  awardingAuthority: [{ required: true, message: '授予单位不能为空', trigger: 'blur' }],
  awardDate: [{ required: true, message: '获得时间不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态 0 未通过 1 审核中 2 通过不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ScholarshipApi.getScholarship(id)
    } finally {
      formLoading.value = false
    }
  } else {
    // 在添加时填充当前登录用户的信息
    try {
      // 调用后端提供的接口获取当前登录用户的信息
      await init()
    } catch (error) {
      // 处理错误
      console.error('Failed to get current user information:', error)
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ScholarshipApi.ScholarshipVO
    if (formType.value === 'create') {
      await ScholarshipApi.createScholarship(data)
      message.success(t('common.createSuccess'))
    } else {
      await ScholarshipApi.updateScholarship(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const init = async () => {
  const userInfo = await getUserProfile()
  // 将获取到的用户信息填充到表单中
  formData.value.major = userInfo.dept.id
  formData.value.studentNumber = userInfo.username
  formData.value.studentName = userInfo.nickname
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    major: undefined,
    studentNumber: undefined,
    studentName: undefined,
    scholarshipCategory: undefined,
    scholarshipName: undefined,
    level: undefined,
    awardingAuthority: undefined,
    awardDate: undefined,
    remark: undefined,
    status: undefined,
    reason: undefined
  }
  formRef.value?.resetFields()
}
</script>
